<template>
  <div class="divBox">
    <div class="selCard ">
      <div class="container">
        <el-form :model="tableFrom" ref="searchForm" size="small" label-width="85px" inline>
          <el-form-item label="订单状态：" style="display: block;" prop="status">
            <el-radio-group v-model="tableFrom.status" type="button" @change="getList(1)">
              <el-radio-button label>全部 {{ '(' +orderChartType.all?orderChartType.all:0 + ')' }}</el-radio-button>
              <el-radio-button label="0">待审核 {{ '(' +orderChartType.audit?orderChartType.audit:0+ ')' }}</el-radio-button>
              <el-radio-button label="-1">审核未通过 {{ '(' +orderChartType.refuse?orderChartType.refuse:0+ ')' }}</el-radio-button>
              <el-radio-button label="1">审核通过 {{ '(' +orderChartType.agree?orderChartType.agree:0+ ')' }}</el-radio-button>
              <el-radio-button label="3">已完成 {{ '(' +orderChartType.end?orderChartType.end:0+ ')' }}</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="时间选择：">
            <el-date-picker v-model="timeVal" value-format="yyyy/MM/dd" format="yyyy/MM/dd" size="small" type="daterange" placement="bottom-end" placeholder="自定义时间" style="width: 280px;" :picker-options="pickerOptions" @change="onchangeTime"/>
          </el-form-item>
          <el-form-item label="退款单号：" prop="refund_order_sn">
            <el-input v-model="tableFrom.refund_order_sn" clearable placeholder="请输入订单号" class="selWidth" @keyup.enter.native="getList(1)"/>
          </el-form-item>
          <el-form-item label="用户：" prop="username">
            <el-input v-model="tableFrom.username" clearable placeholder="请输入用户昵称" class="selWidth" @keyup.enter.native="getList(1)"/>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="getList(1)">搜索</el-button>
            <el-button size="small" @click="searchReset()">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <el-card class="mt14">
      <el-table v-loading="listLoading" :data="tableData.data" size="small" class="table mt20" highlight-current-row>
        <el-table-column label="退款单号" min-width="100">
          <template slot-scope="scope">
            <span style="display: block;" v-text="scope.row.refund_order_sn" />
          </template>
        </el-table-column>
        <el-table-column prop="user.nickname" label="用户信息" min-width="100" />
        <el-table-column prop="refund_price" label="退款金额" min-width="80" />
        <el-table-column prop="nickname" label="商品信息" min-width="260">
          <template slot-scope="scope">
            <div class="tabBox acea-row row-middle">
              <div class="demo-image__preview">
                <el-image :src="scope.row.order.order_info.pic" :preview-src-list="[scope.row.order.order_info.image]"/>
              </div>
              <span class="tabBox_tit">{{ scope.row.order.order_info.activity_name}}</span>
              <span class="tabBox_pice">{{ '￥'+ scope.row.order.order_info.price + ' x 1' }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="user.nickname" label="退款发起方" min-width="90" />
        <el-table-column prop="serviceScore" label="退款单状态" min-width="150">
          <template slot-scope="scope">
            <span style="display: block">{{ scope.row.status | orderRefundFilter }}</span>
            <span v-if="scope.row.status == -1" style="display: block">拒绝原因：{{ scope.row.fail_message }}</span>
            <span style="display: block">退款备注：{{ scope.row.mark }}</span>
            <span style="display: block">状态变更时间：{{ scope.row.status_time }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="150" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="onRefundOrderDetail(scope.row.refund_order_id)">退款单详情</el-button>
            <el-button v-if="scope.row.status === 0" type="text" size="small" @click="onOrderStatus(scope.row.refund_order_id)">退款</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination background :page-size="tableFrom.limit" :current-page="tableFrom.page" layout="total, prev, pager, next, jumper" :total="tableData.total" @size-change="handleSizeChange" @current-change="pageChange"/>
      </div>
    </el-card>
    <!--详情-->
    <details-from ref="orderDetail" :order-datalist="orderDatalist" @get-logistics="openLogistics" />
    <el-dialog title="退款审核" :visible.sync="refundAuditDialogVisible" width="30%" :before-close="handleCloseRefundAudit">
      <el-form :model="refundAuditForm" label-width="80px">
        <el-form-item label="审核结果">
          <el-radio-group v-model="refundAuditForm.status">
            <el-radio label="1">同意</el-radio>
            <el-radio label="-1">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="refundAuditForm.status === '-1'" label="拒绝原因">
          <el-input v-model="refundAuditForm.reason" type="textarea" :rows="4" placeholder="请输入拒绝原因"/>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="handleCloseRefundAudit">取 消</el-button>
    <el-button type="primary" @click="submitRefundAudit">确 定</el-button>
  </span>
    </el-dialog>

  </div>
</template>

<script>
import {
  refundorderDeleteApi,
  refundorderMarkApi,
  refundorderExpressApi,
  confirmReceiptApi,
  refundListImportApi
} from '@/api/order'
import detailsFrom from './refundDetail'
import { roterPre } from '@/settings'
import createWorkBook from '@/utils/newToExcel.js'
import timeOptions from '@/utils/timeOptions';
import { refundActivityDetailApi, refundActivityListApi, refundActivityStatusApi } from '@/api/activity'
// import logisticsFrom from '../logistics'
export default {
  name: 'OrderRefund',
  components: {
    detailsFrom,
    // logisticsFrom
  },
  data() {
    return {
      pickerOptions: timeOptions,
      logisticsName: 'refund',
      dialogLogistics: false,
      orderId: 0,
      tableData: {
        data: [],
        total: 0
      },
      listLoading: true,
      roterPre: roterPre,
      tableFrom: {
        delivery_id: '',
        refund_type: '',
        user_type: '',
        status: '',
        date: '',
        username: '',
        page: 1,
        limit: 20,
        order_sn: this.$route.query.sn ? this.$route.query.sn : '',
        refund_order_sn: this.$route.query.refund_order_sn ? this.$route.query.refund_order_sn : '',
        id: this.$route.query.id ? this.$route.query.id : ''
      },
      orderChartType: {},
      timeVal: [],
      fromList: {
        title: '选择时间',
        custom: true,
        fromTxt: [
          { text: '全部', val: '' },
          { text: '今天', val: 'today' },
          { text: '昨天', val: 'yesterday' },
          { text: '最近7天', val: 'lately7' },
          { text: '最近30天', val: 'lately30' },
          { text: '本月', val: 'month' },
          { text: '本年', val: 'year' }
        ]
      },
      selectionList: [],
      tableFromLog: {
        page: 1,
        limit: 10
      },
      tableDataLog: {
        data: [],
        total: 0
      },
      LogLoading: false,
      dialogVisible: false,
      orderDatalist: null,
      orderDetails: {},
      result: [],
      refundAuditDialogVisible: false,
      refundAuditForm: {
        status: '1',
        reason: ''
      },
      currentRefundOrderId: 0
    }
  },
  mounted() {
    if (this.$route.query.hasOwnProperty('sn')) {
      this.tableFrom.order_sn = this.$route.query.sn
    } else {
      this.tableFrom.order_sn = ''
    }
    this.getList(1)
  },
  // 被缓存接收参数
  activated() {
    if (this.$route.query.hasOwnProperty('sn')) {
      this.tableFrom.order_sn = this.$route.query.sn
    } else {
      this.tableFrom.order_sn = ''
    }
    this.getList(1)
  },
  methods: {
    /**重置 */
    searchReset(){
      this.timeVal = []
      this.tableFrom.date = ""
      this.$refs.searchForm.resetFields()
      this.tableFrom.order_sn = ""
      this.getList(1)
    },
    // 回
    // 订单详情
    onOrderDetail(order_sn) {
      this.$router.push({
        path: this.roterPre + "/order/list",
        query: {
          order_sn: order_sn
        }
      })
    },
    // 退款
    onOrderStatus(id) {
      this.openRefundAuditDialog(id)
      // this.$modalForm(refundActivityStatusApi(id)).then(() => this.getList(''))
    },
    // 确认收货
    confirmReceipt(row) {
      const that = this
      const h = this.$createElement
      this.$msgbox({
        title: '是否确认收货？',
        message: h('div', null, [
          h('p', null, '退货物流公司：' + row.delivery_type),
          h('p', null, '退货快递单号：' + row.delivery_id)
        ]),
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            confirmReceiptApi(row.refund_order_id)
              .then(res => {
                that.$message.success(res.message)
                done()
                that.getList('')
              })
              .catch(({ res }) => {
                that.$message.error(res.message)
              })
          } else {
            done()
          }
        }
      }).then(action => {}).catch(e => e)// 注意这里，这里是重点！！！;
    },
    /**导出退款单 */
    async exports() {
      let excelData = JSON.parse(JSON.stringify(this.tableFrom)), data = []
      excelData.page = 1
      let pageCount = 1
      let lebData = {};
      for (let i = 0; i < pageCount; i++) {
        lebData = await this.downData(excelData)
        pageCount = Math.ceil(lebData.count/excelData.limit)
        if (lebData.export.length) {
          data = data.concat(lebData.export)
          excelData.page++
        }
      }
      createWorkBook(lebData.header, lebData.title, data, lebData.foot,lebData.filename);
      return
    },
    /**资金流水 */
    downData(excelData) {
      return new Promise((resolve, reject) => {
        refundListImportApi(excelData).then((res) => {
          return resolve(res.data)
        })
      })
    },
    getExportFileList() {
      refundListImportApi()
        .then((res) => {
          const h = this.$createElement
          this.$msgbox({
            title: '提示',
            message: h('p', null, [
              h('span', null, '文件正在生成中，请稍后点击"'),
              h('span', { style: 'color: teal' }, '导出记录'),
              h('span', null, '"查看~ ')
            ]),
            confirmButtonText: '我知道了'
          }).then(action => {
            this.$router.push({ path: this.roterPre + '/export/list' })
          })
        })
        .catch((res) => {
          this.$message.error(res.message)
        })
    },
    getTotal(row) {
      let sum = 0
      for (let i = 0; i < row.length; i++) {
        sum += row[i].product ? row[i].product.cart_info.productAttr.price * row[i].refund_num : ''
      }
      return sum
    },
    // 预售商品退款金额
    getPresellTotal(row) {
      let sum = 0
      for (let i = 0; i < row.length; i++) {
        sum += row[i].product ? row[i].product.cart_info.productPresellAttr.presell_price * row[i].refund_num : ''
      }
      return sum
    },
    // 助力商品退款金额
    getAssistTotal(row) {
      let sum = 0
      for (let i = 0; i < row.length; i++) {
        sum += row[i].product ? row[i].product.cart_info.productAssistAttr.assist_price * row[i].refund_num : ''
      }
      return sum
    },
    // 详情
    onRefundOrderDetail(id) {
      this.orderId = id
      this.$refs.orderDetail.dialogVisible = true
      this.loading = true
      refundActivityDetailApi(id)
        .then(res => {
          this.orderDatalist = res.data
          this.loading = false
        })
        .catch(({ message }) => {
          this.loading = false
          this.$message.error(message)
        })
    },
    pageChangeLog(page) {
      this.tableFromLog.page = page
      this.getList('')
    },
    handleSizeChangeLog(val) {
      this.tableFromLog.limit = val
      this.getList('')
    },
    // 订单删除
    handleDelete(row, idx) {
      if (row.is_del === 1) {
        this.$modalSure().then(() => {
          refundorderDeleteApi(row.refund_order_id)
            .then(({ message }) => {
              this.$message.success(message)
              this.tableData.data.splice(idx, 1)
            })
            .catch(({ message }) => {
              this.$message.error(message)
            })
        })
      } else {
        this.$confirm(
          '您选择的订单存在用户未删除的订单，无法删除用户未删除的订单！',
          '提示',
          {
            confirmButtonText: '确定',
            type: 'error'
          }
        )
      }
    },
    // 备注
    onOrderMark(id) {
      this.$modalForm(refundorderMarkApi(id)).then(() => this.getList(''))
    },
    // 选择时间
    selectChange(tab) {
      this.tableFrom.date = tab
      this.timeVal = []
      this.getList(1)
    },
    // 具体日期
    onchangeTime(e) {
      this.timeVal = e
      this.tableFrom.date = e ? this.timeVal.join('-') : ''
      this.getList(1)
    },
    // 列表
    getList(num) {
      this.listLoading = true
      this.tableFrom.page = num || this.tableFrom.page
      refundActivityListApi(this.tableFrom)
        .then(res => {
          this.orderChartType = res.data.stat
          this.tableData.data = res.data.list
          this.tableData.total = res.data.count
          this.listLoading = false
        })
        .catch(res => {
          this.$message.error(res.message)
          this.listLoading = false
        })
    },
    pageChange(page) {
      this.tableFrom.page = page
      this.getList()
    },
    handleSizeChange(val) {
      this.tableFrom.limit = val
      this.getList()
    },
    openLogistics(row) {
      this.orderDetails = row
      this.getOrderData(row.refund_order_id)
      this.dialogLogistics = true
    },
    handleClose() {
      this.dialogLogistics = false
      this.dialogConfirm = false
    },
    // 获取订单物流信息
    getOrderData(id) {
      refundorderExpressApi(id)
        .then(async res => {
          this.result = res.data
        })
        .catch(res => {
          this.$message.error(res.message)
        })
    },
    openRefundAuditDialog(refundOrderId) {
      this.currentRefundOrderId = refundOrderId
      this.refundAuditDialogVisible = true
      this.refundAuditForm.status = '1'
      this.refundAuditForm.reason = ''
    },
    handleCloseRefundAudit() {
      this.refundAuditDialogVisible = false
    },
    submitRefundAudit() {
      const { status, reason } = this.refundAuditForm
      const refundOrderId = this.currentRefundOrderId
      const params = {
        id: refundOrderId,
        status: parseInt(status),
        fail_message: status === '-1' ? reason : ''
      }
      refundActivityStatusApi(refundOrderId, params)
        .then(({ message }) => {
          this.$message.success(message)
          this.handleCloseRefundAudit()
          this.getList('')
        })
        .catch(({ message }) => {
          this.$message.error(message)
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.demo-table-expands ::v-deep label {
  width: 110px !important;
  color: #99a9bf;
}
::v-deep .el-input--suffix .el-input__inner{
  padding-right: 10px;
}
.el-icon-arrow-down {
  font-size: 12px;
}
.tabBox_tit {
  max-width: 60%;
  font-size: 12px !important;
  margin: 0 2px 0 10px;
  letter-spacing: 1px;
  padding: 5px 0;
  box-sizing: border-box;
}
</style>
